var app = getApp();
var time = require('../../utils/util.js');
Page({
  data: {
    userInfo: app.globalData.bookUrl + '/user/userInfo.do', //注册
    userRegister: app.globalData.bookUrl + '/user/userRegister.do', //获取用户信息
    notReturned: app.globalData.bookUrl + '/user/getBorrowing.do', //获取当前用户未归还图书id
    getBooksByCondition: app.globalData.bookUrl + '/book/getBooks.do', //根据图书id获取图书信息
    getBookType: app.globalData.bookUrl + '/book/bookType.do',
    backBook: app.globalData.bookUrl + '/user/backBook.do',
    selectRecommendURL: app.globalData.bookUrl + '/Recommend/selectRecommend.do',
    
    length: 0,
    currentPage: 1,
    recommendCurrentPage:1,
    booklist: [],
    recommendList: [],
    hiddenmodalput: true,
    trueName: "",
    readerNameing: "",
    personalTab: 0,
    winWidth: 0,
    winHeight: 0,
    height: 0,
  },
  //弹框
  modalinput: function() {
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    })
  },
  //取消按钮  
  cancel: function() {
    this.setData({
      hiddenmodalput: true
    });
  },
  //确认  
  confirm: function() {
    var that = this;
    if (that.data.readerNameing == "") {
      wx.showToast({
        title: '请填写姓名',
        image: '../../images/icon/fail.png',
        duration: 2000
      })
      that.setData({
        hiddenmodalput: !that.data.hiddenmodalput
      })
    } else {
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000
      })
      this.setData({
        hiddenmodalput: true
      })
      wx.getStorage({
        key: 'openid',
        success(res) {
          that.userRegister(res.data);
        }
      })
    }
  },
  userRegister: function(openId) {
    var that = this;
    var readerName = that.data.readerNameing;
    wx.request({
      url: that.data.userRegister,
      data: {
        openId: openId,
        readersName: readerName
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        wx.showToast({
          title: res.data.data ? '修改成功' : '修改失败',
          duration: 1500,
          icon: 'success'
        })
        if (res.data.data) {
          that.setData({
            trueName: readerName
          });
        }
      },
      fail: function(error) {
        // fail
        console.log(error)
      }
    })
  },
  getReadersName: function(e) {
    var that = this;
    that.setData({
      readerNameing: e.detail.value
    });
  },
  // 下拉刷新
  onPullDownRefresh: function() {
    // 显示顶部刷新图标
    var that = this;
    wx.showNavigationBarLoading();
    this.setData({
      currentPage: 1,
      booklist: [],
      recommendCurrentPage:1,
      recommendList: [],
    });
    wx.showNavigationBarLoading({
      title: '正在刷新',
    })
    // 页数+1
    var getBookType = that.data.getBookType;
    that.getBookType(getBookType); //获取图书类别
    wx.getStorage({
      key: 'openid',
      success(res) {
        that.getNotReturned(that.data.notReturned, res.data, 1);
        that.getMyRecommend(res.data, 1,'yes');
      }
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  lower: function() {
    var that = this;
    if (that.data.personalTab == 0) {
      var result = that.data.booklist;
      if (result.length == that.data.length) { //最大数值
        wx.showToast({
          title: "已到达底部",
          icon: "success",
          duration: 300
        });
        return false;
      } else {
        // 显示加载图标
        var getLoseBooks = app.globalData.bookUrl + '/book/getBooks.do'; //获取图书URL
        var currentPage = that.data.currentPage;
        wx.getStorage({
          key: 'openid',
          success(res) {
            that.getNotReturned(that.data.notReturned, res.data, currentPage);
          }
        })
     }
    }else{
      var recommendResult = that.data.recommendList;
      if (recommendResult.length == that.data.totalElements) { //最大数值
        wx.showToast({
          title: "已到达底部",
          icon: "success",
          duration: 300
        });
        return false;
      } else {
        var recommendCurrentPage = that.data.recommendCurrentPage;
        wx.getStorage({
          key: 'openid',
          success(res) {
            that.getMyRecommend(res.data, recommendCurrentPage,'no');
          }
        })
      }
    }

  },
  onShow:function(options){
    var that = this;
    var getBookType = that.data.getBookType;
    that.getBookType(getBookType); //获取图书类别
    wx.getStorage({
      key: 'openid',
      success(res) {
        that.userInfo(res.data);
        that.getNotReturned(that.data.notReturned, res.data, 1);
        that.getMyRecommend(res.data, 1,'yes');
      }
    })
  },
  onLoad: function (options) {
    //2019.3.12
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        console.log(res.windowHeight)
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });

    var query = wx.createSelectorQuery();
    query.select('.personage_top').boundingClientRect()
    query.exec(function (res) {
      console.log(res[0].height);
      that.setData({
        height: res[0].height
      })
    });
  },
  /**
   * 获取用户信息
   */
  userInfo: function(openId) {
    var that = this;
    var userInfo = that.data.userInfo; //拿到是第几个数组
    wx.request({
      url: userInfo,
      data: {
        openId: openId
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        if (res.data.data.content != null) {
          that.setData({
            trueName: res.data.data.content[0].readersName
          });
        }
      },
      fail: function(error) {
        console.log(error)
      }
    })

  },
  bindback: function(e) {
    var bookId = e.currentTarget.dataset.bookid;
    var bookIndex = e.currentTarget.dataset.bookindex; //拿到是第几个数组
    var that = this;
    wx.getStorage({
      key: 'openid',
      success(res) {
        var openId = res.data
        that.backBook(openId, bookId, bookIndex);
      }
    })
  },
  backBook: function(openId, bookId, bookIndex) {
    var that = this;
    wx.request({
      url: that.data.backBook,
      data: {
        bookId: bookId,
        openId: openId
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        if (res.data.code == 0) {
          wx.showToast({
            title: '归还成功',
            duration: 1000,
            icon: 'success'
          })
          that.setData({
            bookState: 1
          });
        } else if (res.data.code == -3003) {
          wx.showToast({
            title: '不能归还',
            duration: 1000,
            image: '../../images/icon/fail.png',
          })
        }
        if (res.data.data) {
          var books = that.data.booklist;//.splice(bookIndex, 1);
          for (var idx in books) {
            if (books[idx].bookId == bookId){
              books.splice(idx, 1);
              break;
            }
          }
          that.setData({
            booklist: books
          });
        }
      },
      fail: function(error) {
        // fail
        console.log(error)
      }
    })
  },
  getMyRecommend: function (openId, recommendCurrentPage, refresh) {

    var that = this;
    if (refresh == "yes") {
      that.setData({
        recommendList: [],
      })
    }
    wx.request({
      url: that.data.selectRecommendURL,
      data: {
        openid: openId,
        currentPage: recommendCurrentPage,
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        that.showMyRecommend(res.data.data); //向前台传递数据
        if (res.data.data != null) {
          that.setData({
            recommendCurrentPage: recommendCurrentPage + 1,
            totalElements: res.data.data.totalElements
          });
        }
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
  },
  showMyRecommend: function (recommend) {
    var that = this;
    var recommends = that.data.recommendList;
    if (recommend != null) {
      for (var idx in recommend.content) {
        var content = recommend.content[idx];
        var bookName = content.bookName;
        var bookAuthor = content.bookAuthor;
        var recommendImg = app.globalData.bookUrl + content.recommendImg + '?' + Math.random() / 9999;
        var allreadersName = content.allreadersName;
        var recommendReason = content.recommendReason;
        var recommendId = content.recommendId;
        var isfristRecommend = content.isfristRecommend;
        var createTime = time.formatTime(content.createTime, 'Y-M-D h:m:s');
        var temp = {
          allreadersName: allreadersName,
          createTime: createTime,
          bookName: bookName,
          recommendId: recommendId,
          recommendReason: recommendReason,
          recommendImg: recommendImg,
          isfristRecommend: isfristRecommend,
          bookAuthor: bookAuthor,
        }
        recommends.push(temp);
      }
      that.setData({
        recommendList: recommends
      });
      wx.hideLoading({
        title: '玩命加载中',
      })
    } else {
      // wx.showToast({
      //   title: "没有新推荐",
      //   image: '../../images/icon/fail.png',
      //   duration: 1500
      // })
    }
  },
  getBookType: function(getBookType) {
    var that = this;
    wx.request({
      url: getBookType,
      data: {},
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        that.showBookType(res.data.data); //向前台传递数据
      },
      fail: function(error) {
        // fail
        console.log(error)
      }
    })
  },
  showBookType: function(allBookType) {
    var that = this;
    var bookType = [];
    bookType.push("全部");
    if (allBookType.size > 0) {
      for (var idx in allBookType.content) {
        var content = allBookType.content[idx];
        var bookTypeName = content.bookTypeName;
        bookType.push(bookTypeName);
        that.setData({
          bookTypeList: bookType
        });
      }
    } else {
      console.log("暂无状态");
    }
  },
  getNotReturned: function(notReturnedURL, openId, currentPage) {
    var that = this;
    wx.request({
      url: notReturnedURL,
      data: {
        openId: openId,
        currentPage: currentPage
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        that.getBorrowingBooks(res.data.data); //根据类别获取全部图书
        if (res.data.data != null) {
          that.setData({
            currentPage: currentPage + 1,
            length: res.data.data.length,
          });
        }
        wx.hideNavigationBarLoading({
          title: '正在刷新',
        })
      },
      fail: function(error) {
        // fail
        console.log(error)
      }
    })
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },
  getBorrowingBooks: function(allBorrowingBooks) {
    var that = this;
    var books = [];
    if (allBorrowingBooks.length > 0) {
      for (var idx in allBorrowingBooks) {
        var content = allBorrowingBooks[idx];
        var bookImgSource = app.globalData.bookUrl + content.bookImg;
        var borrowingTimeSource = time.formatTime(content.borrowingTime, 'Y-M-D h:m:s');
        var bookStateSource = content.bookState;
        var nowDate = time.nowFormatTime(new Date());
        var borrow_date = new Date(borrowingTimeSource.replace(/-/g, "/"));
        var now_date = new Date(nowDate.replace(/-/g, "/"));
        var days = now_date.getTime() - borrow_date.getTime();
        var day = parseInt(days / (1000 * 60 * 60 * 24))+1;
        if (day <= 15) {
          that.setData({
            thirtyDays: 0
          });
        }
        if (day > 15&&day<=25) {
          that.setData({
            thirtyDays: 1
          });
        }
        if(day>30){
          that.setData({
            thirtyDays: 2
          });
        }
        var temp = {
          bookIndex: idx,
          bookId: content.bookId,
          bookImg: bookImgSource,
          bookName: content.bookName,
          borrowingTime: borrowingTimeSource,
          bookAuthor: content.bookAuthor,
        }
        books.push(temp);
        that.setData({
          borrowDays: day,
          booklist: books
        });
      }
    } else {
      console.log("没有丢失");
    }
  },
  updateRecommend: function (e) {
    var bookName = e.currentTarget.dataset.bookname;
    var bookAuthor = e.currentTarget.dataset.bookauthor;
    var recommendId = e.currentTarget.dataset.recommendid;
    var recommendReason = e.currentTarget.dataset.recommendreason;
    var isfristRecommend = e.currentTarget.dataset.isfristrecommend;
    var recommendImg = e.currentTarget.dataset.recommendimg;
    wx.navigateTo({
      url: "../recommend/myRecommend/myRecommend?bookName=" + bookName + "&bookAuthor=" + bookAuthor + "&recommendToo=3" + "&recommendId=" + recommendId + "&recommendReason=" + recommendReason + "&isfristRecommend=" + isfristRecommend + "&recommendImg=" + recommendImg
    })
  },
  bindChange: function (e) {
    var that = this;
    that.setData({ personalTab: e.detail.current });
  },
  swichNav: function (e) {
    var that = this;
    if (this.data.personalTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        personalTab: e.target.dataset.current
      })
    }
  }
})